from django.utils.deprecation import MiddlewareMixin
from course import views as course_views
from django.shortcuts import reverse

class MyMiddleware(MiddlewareMixin):
    def __init__(self,get_response=None):
        super().__init__(get_response)
        # 初始化中间件
        print('init_mymiddleware')

    def process_request(self,request):
        # 在request对象中添加一个context字典
        request.context = {}
        session_user = None
        # 如果session中有session_user
        if 'session_user' in request.session.keys():
            # 把session中的session_user添加到request.context中
            session_user = request.context['session_user'] = request.session['session_user']
        if not session_user:
            if request.path.startswith('/video')  or request.path.startswith('/user'):
                if request.path not in [reverse('user_login'),reverse('user_register')]:
                    request.context['login_message'] = '请先登录'
                    return course_views.index_handler(request)

        '''
        中间件的安全性能维护
        request.context = dict(
            session_user = request.session['session_user']
        )
        if (not request.context['session_user']) \
            and (request.path.startswith('/video') or request.path.startswith('/user')
            and  request.path not in [reverse('user_login'),reverse('user_register')]
             )
             request.context['login_message'] = '请先登录'
                    return course_views.index_handler(request)
        '''


    def process_response(self,request,response):
        # 必须return response
        print('process_response')
        return response